import { useStore } from "@/store";
import { computed, ComputedRef, onMounted, onUnmounted, ref, Ref } from "vue";
import { useRouter, type Router } from "vue-router";
import { Commit } from "vuex";

export function useClickOutside(
  elementRef: Ref<HTMLElement | null>
): Ref<boolean> {
  const isClickOutside = ref(false);

  const handler = (e: MouseEvent) => {
    if (elementRef.value) {
      if (elementRef.value.contains(e.target as HTMLElement)) {
        isClickOutside.value = false;
      } else {
        isClickOutside.value = true;
      }
    }
  };
  onMounted(() => {
    document.addEventListener("click", handler);
  });
  onUnmounted(() => {
    document.removeEventListener("click", handler);
  });

  return isClickOutside;
}

export interface LoadParams {
  pageSize: number;
  currentPage: number;
}
export const useLoadMore = (
  actionName: string,
  total: ComputedRef<number>,
  params: LoadParams = {
    pageSize: 3,
    currentPage: 1,
  }
): [ComputedRef<boolean>, () => void, Ref<number>] => {
  const store = useStore();
  const router = useRouter();
  const currentPage = ref(params.currentPage);
  const loadMorePage = async () => {
    await store.dispatch(actionName, {
      currentPage: currentPage.value,
      pageSize: params.pageSize,
      router,
    });
    currentPage.value++;
  };
  const isLastPage = computed(
    () => Math.ceil(total.value / params.pageSize) < currentPage.value
  );

  return [isLastPage, loadMorePage, currentPage];
};

export const useHttpErrorHandler = (router: Router, commit: Commit) => {
  const handleResponse = (resp: Response) => {
    if (resp.status >= 400 && resp.status < 500) {
      return Promise.reject(resp);
    }

    return resp.json();
  };
  const handleError = (error: HttpError) => {
    if (error.status === 401) {
      commit("logout");
      router.push("/login");
    } else {
      console.error("HTTP Error:", error);
    }
  };

  return {
    handleError,
    handleResponse,
  };
};
